using ETask.Api.Data;
using ETask.Api.Dtos;
using ETask.Api.Models;
using ETask.Api.Repositories;

namespace ETask.Api.Services
{
    public class ProjectMemberService : IProjectMemberService
    {
        private readonly IProjectRepository _projectRepository;
        private readonly IUserRepository _userRepository;

        public ProjectMemberService(IProjectRepository projectRepository, IUserRepository userRepository)
        {
            _projectRepository = projectRepository;
            _userRepository = userRepository;
        }

        public async Task<ApiResponse> AddProjectMembers(int projectId, List<ProjectMemberDto> userList)
        {
            try
            {
                // 验证项目是否存在
                var project = await _projectRepository.GetByIdAsync(projectId);
                if (project == null)
                {
                    return ApiResponse.Fail(400, "项目不存在");
                }

                if (userList == null || userList.Count == 0)
                {
                    return ApiResponse.Fail(400, "用户信息缺失");
                }

                // 验证用户是否存在
                foreach (var item in userList)
                {
                    var user = await _userRepository.GetByIdAsync(item.UserId);
                    if (user == null)
                    {
                        return ApiResponse.Fail(400, $"用户ID {item.UserId} 不存在");
                    }

                    // 检查用户是否已经是项目成员
                    var exists = await _projectRepository.CheckMemberExists(projectId, item.UserId);
                    if (exists)
                    {
                        return ApiResponse.Fail(400, $"用户 {user.Name} 已经是项目成员");
                    }
                }

                var loginUser = UserContext.CurrentUser;
                List<ProjectMember> members = userList.Select(q => new ProjectMember
                {
                    ProjectId = projectId,
                    UserId = q.UserId,
                    Role = q.Role,
                    CreatedAt = DateTime.Now,
                    CreateBy = loginUser.Id
                }).ToList();

                int rows = await _projectRepository.AddUserListAsync(members);
                return ApiResponse.Ok($"成功添加 {rows} 个成员");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"添加项目成员失败: {ex.Message}");
            }
        }

        public async Task<ApiResponse> DeleteProjectMember(int id)
        {
            try
            {
                var result = await _projectRepository.DelProjectUserById(id) > 0;
                return ApiResponse.Ok(result ? "删除成功" : "删除失败");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"删除项目成员失败: {ex.Message}");
            }
        }

        public async Task<ApiResponse> UpdateProjectMember(ProjectMemberDto memberDto)
        {
            try
            {

                ProjectMember projectMember = await _projectRepository.GetMemberById(memberDto.Id);
                if (projectMember == null)
                {
                    return ApiResponse.Fail(400, "成员不存在");
                }
                projectMember.Role = memberDto.Role;
                projectMember.UpdateBy = UserContext.CurrentUser.Id;
                projectMember.UpdatedAt = DateTime.Now;
                var result = await _projectRepository.UpdateProjectUser(projectMember) > 0;
                return ApiResponse.Ok(result ? "更新成功" : "更新失败");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"更新项目成员失败: {ex.Message}");
            }
        }

        public async Task<ApiResponse> GetProjectMembers(int projectId)
        {
            try
            {
                var members = await _projectRepository.GetProjectMembers(projectId);
                return ApiResponse.Ok(members);
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"获取项目成员失败: {ex.Message}");
            }
        }

        public async Task<ApiResponse> BatchAddProjectMembers(int projectId, List<int> userIds, string role = "developer")
        {
            try
            {
                if (userIds == null || userIds.Count == 0)
                {
                    return ApiResponse.Fail(400, "用户ID列表不能为空");
                }

                // 验证项目是否存在
                var project = await _projectRepository.GetByIdAsync(projectId);
                if (project == null)
                {
                    return ApiResponse.Fail(400, "项目不存在");
                }

                var loginUser = UserContext.CurrentUser;
                var members = new List<ProjectMember>();

                foreach (var userId in userIds)
                {
                    // 验证用户是否存在
                    var user = await _userRepository.GetByIdAsync(userId);
                    if (user == null)
                    {
                        continue; // 跳过不存在的用户
                    }

                    // 检查用户是否已经是项目成员
                    var exists = await _projectRepository.CheckMemberExists(projectId, userId);
                    if (exists)
                    {
                        continue; // 跳过已是成员的用户
                    }

                    members.Add(new ProjectMember
                    {
                        ProjectId = projectId,
                        UserId = userId,
                        Role = role,
                        CreatedAt = DateTime.Now,
                        CreateBy = loginUser.Id
                    });
                }

                if (members.Count == 0)
                {
                    return ApiResponse.Fail(400, "没有可添加的新成员");
                }

                int rows = await _projectRepository.AddUserListAsync(members);
                return ApiResponse.Ok($"成功添加 {rows} 个成员");
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"批量添加项目成员失败: {ex.Message}");
            }
        }

        public async Task<ApiResponse> CheckMemberExists(int projectId, int userId)
        {
            try
            {
                var exists = await _projectRepository.CheckMemberExists(projectId, userId);
                return ApiResponse.Ok(new { exists });
            }
            catch (Exception ex)
            {
                return ApiResponse.Fail(500, $"检查成员存在性失败: {ex.Message}");
            }
        }
    }
}
